<?php

namespace app\admin\controller\rush;

use app\admin\model\rush\Order;
use app\admin\model\rush\Time;
use app\api\model\RushOrderAddress;
use app\api\model\RushOrderEntrust;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 抢购商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\rush\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\rush\Goods;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->assignconfig("splitorder_limit", config('site.splitorder_limit'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map = [];
            $rush_user_id = $this->request->get('rush_user_id');
            if($rush_user_id){
                $order_ids = Order::where('buyer_id',$rush_user_id)->column('id');
                $map[$this->model->getTable().'.id'] = ['in',$order_ids];
            }
            $list = $this->model
                    ->with(['category','time','seller','buyer','order'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','goods_no','image','images','original_price','current_price','status','weigh']);
                $row->visible(['category']);
				$row->getRelation('category')->visible(['name']);
				$row->visible(['time']);
				$row->getRelation('time')->visible(['name']);
				$row->visible(['seller']);
				$row->getRelation('seller')->visible(['nickname','mobile','bank_name','bank_card_no','bank_card_holder']);
				$row->visible(['buyer']);
				$row->getRelation('buyer')->visible(['nickname','mobile','bank_name','bank_card_no','bank_card_holder']);
				$row->visible(['order']);
				$row->getRelation('order')->visible(['payment_voucher']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $params['current_price'] <= 0 && $this->error('商品金额不能小于等于0');
                //初始价格
                $params['original_price'] = $params['current_price'];
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    //生成初始订单
                    $order = Order::create([
                        'seller_id' => $params['seller_id'],
                        'order_no' => get_order_sn('R'),
                        'order_status' => '3', //状态直接设置为已委托上架
                        'goods_id' => $this->model->id,
                        'goods_name' => $params['name'],
                        'goods_no' => $params['goods_no'],
                        'goods_price' => $params['current_price'],
                        'goods_image' => $params['image'],
                        'time_id' => $params['time_id'],
                        'time_name' => Time::where('id',$params['time_id'])->value('name'),
                    ]);
                    //修改订单当前ID
                    $this->model->where('id',$this->model->id)->update(['current_order_id'=>$order['id']]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    //订单还没卖出，就修改订单信息
                    $order = Order::get($row['current_order_id']);
                    if($order['order_status'] != '4' && $order['new_order_id'] == 0){
                        $order->save([
                            'seller_id' => $params['seller_id'],
                            'goods_name' => $params['name'],
                            'goods_no' => $params['goods_no'],
                            'goods_price' => $params['current_price'],
                            'goods_image' => $params['image'],
                            'time_id' => $params['time_id'],
                            'time_name' => Time::where('id',$params['time_id'])->value('name'),
                        ]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 拆单
     */
    public function splitorder($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $params['current_price'] <= 0 && $this->error('商品金额不能小于等于0');
                $edit_current_price = $row['current_price'] - $params['current_price'];
                $edit_current_price <= 0 && $this->error('商品金额只能小于原商品金额');
                //初始价格
                $params['original_price'] = $params['current_price'];
                //延续父订单卖家
                $params['seller_id'] = $row['seller_id'];
                //拆单父ID
                $params['split_pid'] = $ids;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //修改原商品的价格
                    $result = $row->allowField(true)->save(['current_price'=>$edit_current_price]);
                    Order::where('id',$row['current_order_id'])->update(['goods_price'=>$edit_current_price]);
                    //拆出一个新的商品和订单
                    $this->model->isUpdate(false)->save($params);
                    $order = Order::create([
                        'seller_id' => $row['seller_id'],
                        'order_no' => get_order_sn('R'),
                        'order_status' => '3', //状态直接设置为已委托上架
                        'goods_id' => $this->model->id,
                        'goods_name' => $params['name'],
                        'goods_price' => $params['current_price'],
                        'goods_image' => $params['image'],
                        'time_id' => $params['time_id'],
                        'time_name' => Time::where('id',$params['time_id'])->value('name'),
                    ]);
                    //修改订单当前ID
                    $this->model->where('id',$this->model->id)->update(['current_order_id'=>$order['id']]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                //删除对应订单
                $order_ids = Order::where('goods_id',$v['id'])->column('id');
                RushOrderAddress::where('order_id','in',$order_ids)->delete();
                RushOrderEntrust::where('order_id','in',$order_ids)->delete();
                Order::where('goods_id',$v['id'])->delete();
                $count += $v->delete(true);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
